from gluon.validators import Validator

"""
This file is part of PeerTool, a web application for collaborative
decision-making (Copyrighted, 2009-2010, Ellis & Grant, Inc.)
Developed by Michael F. Ellis <michael.f.ellis@gmail.com>.  
License: AGPL v3
PeerTool comes with ABSOLUTELY NO WARRANTY.
"""                
class IS_NOT_EMPTY_HTML(Validator):
    """
    Custom validator used with fields that return html text. Removes all tags
    and tests to see if what remains is an empty string.
    """

    def __init__(self, error_message='Enter some text'):
        debug('in __init__')
        self.error_message = error_message

    def __call__(self, value):
        debug('value=%s'%value)
        if ptproblem.isEmptyHtml(value):        
            debug('empty!')
            return (value, self.error_message)
        else:    
            debug('not empty')
            return (value, None)


@auth.requires_login()
def index():
    debug("Entering ...")
    if request.args and request.args[0] != None:
        session.problemid = int(request.args[0])
    problem = loadProblem(session.problemid)
    if problem==None:
        redirect(URL(r=request, c='choose', f='index'))
    editexisting = len(problem.lastresponses)<2 ## editable if only one 
                                                # user on team  
    debug("Leaving ...")    
    return dict(problem=problem, editexisting=editexisting)


@auth.requires_login()
def edititem():
    """ 
    Page where users enter and edit text for problem des:wqcriptions, solutions,
    and criteria.  
    """
    itemtype = request.vars.itemtype
    itemid = request.vars.itemid
    debug("Entering edititem(%(itemtype)s, %(itemid)s)"%locals())
    problem = loadProblem(session.problemid)
    if itemtype == 'solution':
        itemtext = problem.solutions[itemid].text
        update = lambda t: problem.solutions[itemid].updateText(t)
        title = "Edit solution"                 # for header at top of page.
        merge = False                           # won't 
    elif itemtype == 'new_solution':
        itemtext = ''
        update = lambda t: problem.addSolution(ptproblem.Solution(t))
        title = "New solution"
        merge = True
    elif itemtype == 'criterion':
        itemtext = problem.criteria[itemid].text
        update = lambda t: problem.criteria[itemid].updateText(t)
        title = "Edit criterion"
        merge = False
    elif itemtype == 'new_criterion':
        itemtext = ''
        title = 'New criterion'
        update = lambda t: problem.addCriterion(ptproblem.Criterion(t))
        merge = True
    elif itemtype == 'description':
        itemtext = problem.text
        update = lambda t: problem.updateText(t)
        title = "Edit"
        merge = False
    else:
        raise ValueError("Unsupported itemtype: %s"%itemtype)

    fields = [Field("edited", 'text', default=itemtext,
                    requires=IS_NOT_EMPTY_HTML(),
                    )
             ]
    form = SQLFORM.factory(*fields)
    if form.accepts(request.vars, session):
        session.flash = 'Edit accepted.'
        #import pdb; pdb.set_trace()
        update(form.vars.edited)
        if merge:
            mergeadditions(problem, problemid=session.problemid)
        else:
            updateProblem(session.problemid, problem)

        redirect(URL(r=request,f='index'))

    elif form.errors:
        response.flash = 'Form has errors!'
    else:
        response.flash = 'Fill out the form'
    return dict(form=form, title=title)
